import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../config/config.dart';
import '../../hj_model/home/home_tabs_entity.dart';
import '../../hj_utils/light_model.dart';
import '../../tools_base/debug_log.dart';

class HomeMainLogic extends GetxController with GetTickerProviderStateMixin {

  String get _localSortKey => "_localSortKey_Tab_ID_cache_$isDarkStyle";

  final bool isDarkStyle;
  final String? darkDefaultId; // 暗网跳转到指定的tab使用
  HomeMainLogic({
    this.isDarkStyle = false,
    this.darkDefaultId,
  });
  //tabController: 因为菜单可以排序导致tab会多次初始化,TickerProviderStateMixin只能绑定一个对象, dispose也不能释放,所以放到外部处理
  TabController? tabController;
  bool isLoadingData = true;
  GlobalKey<ScaffoldState> globalKey = GlobalKey();
  int _initTabIndex = 0; // 注意⚠️:暗网进入,有可能通过内链指定亚模块进入,index通过defaultId 处理
  int tabViewValueKey = 0;

  List<ModuleData> _curSortTabArr = [];
  List<ModuleData> _localSortTabArr = [];

  List<ModuleData> get defaultList {
    if (isDarkStyle) {
      return Config.plateModule?.deepWeb ?? [];
    } else {
      return Config.plateModule?.videosUI ?? [];
    }
  }

  int get selectedTabIndex {
    return tabController?.index ?? _initTabIndex;
  }

  List<ModuleData> get homePageTabArr {
    if (_curSortTabArr.isNotEmpty) return _curSortTabArr;
    List<ModuleData> homePageArr = [];
    homePageArr.addAll(_localSortTabArr);
    for (int i = 0; i < defaultList.length; i++) {
      ModuleData model = defaultList[i];
      bool isExist = false;
      for (var localModel in _localSortTabArr) {
        if (model.id == localModel.id) {
          isExist = true;
        }
      }
      if (!isExist) {
        homePageArr.add(model);
      }
    }
    return homePageArr;
  }

  @override
  void onInit() {
    super.onInit();
    loadLocalData();
  }

  void loadLocalData() async {
    try {
      List<String> jsonList = await lightKV.getStringList(_localSortKey) ?? [];

      if (jsonList.isNotEmpty) {
        _localSortTabArr = jsonList.map((e) => ModuleData.fromJson(json.decode(e))).toList();
      }
      List<ModuleData> removeData = [];
      for (int i = 0; i < _localSortTabArr.length; i++) {
        ModuleData localModel = _localSortTabArr[i];
        bool isExist = false;
        for (int i = 0; i < defaultList.length; i++) {
          ModuleData model = defaultList[i];
          if (localModel.id == model.id) {
            isExist = true;
          }
        }
        if (!isExist) {
          removeData.add(localModel);
        }
      }
      for (var model in removeData) {
        _localSortTabArr.remove(model);
      }
      saveLocalData(_localSortTabArr);
      if (darkDefaultId?.isNotEmpty == true) {
        for (int i = 0; i < _localSortTabArr.length; i++) {
          if (_localSortTabArr[i].id == darkDefaultId) {
            _initTabIndex = i;
            break;
          }
        }
      }
    } catch (e) {
      debugLog(e);
    }
    _localSortTabArr = [];
    isLoadingData = false;
    update();
  }

  void openDrawer() {
    globalKey.currentState?.openDrawer();
  }

  void skipToTabInitIndex() {
    tabController?.index = _initTabIndex;
  }

  void gotoTabId(String tagDataId) {
    for (int i = 0; i < homePageTabArr.length; i++) {
      if (tagDataId == homePageTabArr[i].id) {
        tabController?.index = i;
        return;
      }
    }
  }

  Future gotoTabDataAndResort(List<ModuleData> dataArr, ModuleData? tagData) async {
    bool isSameArr = true;
    ModuleData curTagData = tagData ?? homePageTabArr[selectedTabIndex];
    int selectIndex = 0;
    if (dataArr.length == homePageTabArr.length) {
      for (int i = 0; i < dataArr.length; i++) {
        if (dataArr[i].moduleName != homePageTabArr[i].moduleName) {
          isSameArr = false;
        }
        if (dataArr[i].moduleName == curTagData.moduleName) {
          selectIndex = i;
        }
      }
    }
    if (isSameArr) {
      tabController?.index = selectIndex;
    } else {
      await saveLocalData(dataArr);
      tabViewValueKey++;
      _curSortTabArr = dataArr;
      _initTabIndex = selectIndex;
      tabController = null;
      //tabTopStore.mainTopNotification(false);
      update();
    }
  }

  Future saveLocalData(List<ModuleData> dataArr) async {
    List<String> jsonList = dataArr.map((e) => json.encode(e.toJson())).toList();
    await lightKV.setStringList(_localSortKey, jsonList);
  }

  @override
  void onClose() {
    super.onClose();
  }
}
